<?php defined('MINICAKE') or exit('can not access!');

	class Router  {
		private $default_controller = 'index';
		private $default_action = 'index';
		private $uri_segmentation = '/';
		private $uri_argvs = array();
		private $uri = '';
		private $controller = '';
		private $action = '';
		private $route = '';
		private $route_array = array();//route中的action的数组
		
		public function __construct($uri){
			$this->uri_segmentation = Configure::getItem('uri_segmentation');
			$this->default_controller = Configure::getItem('default_controller');
			$this->default_action = Configure::getItem('default_action');
			Configure::load('route');
			$this->route = Configure::getItems('route');
			$this->route_array = Configure::getRouteArray();
			$this->uri = $uri;
			$this->_parseUri();
		}
		
		private function _parseUri(){
			//处理一下uri前后的 '/'
			if((substr($this->uri,-1) === '/')){
				if($this->uri !== '/'){
					$this->uri = substr($this->uri,1,-1);
				}
			}else{
				$this->uri = substr($this->uri,1);
			}
			
			if($this->uri === '/'){
					//为根目录的时候
					$this->uri_argvs[0] = $this->controller = $this->default_controller;
					$this->uri_argvs[1] = $this->action = $this->default_action;
			}else{
				$temp_uri = explode($this->uri_segmentation,$this->uri);
				if(empty($this->route) or !in_array($temp_uri[0],$this->route_array)){
					//如果没有设置route，将会是/controller/action/argvs/的顺序
					if(count($temp_uri)== 1){
						//如果只有controller的时候
						$this->uri_argvs[0] = $this->controller = $temp_uri[0];
						$this->uri_argvs[1] = $this->action = $this->default_action;
					}else{
						$this->uri_argvs = & $temp_uri;
						$this->controller = $temp_uri[0];
						$this->action = $temp_uri[1];
					}
				}else{
					//如果设置了路由，这里进行路由的匹配
					foreach ($this->route as $key => $val) {
						$key = str_replace(':any','.+',$key);
						$key = str_replace(':num','[0-9]+',$key);
						
						if(preg_match('#^'.$key.'$#',$this->uri)){
							$val = preg_replace('#^'.$key.'$#',$val,$this->uri);
							$temp_uri = explode($this->uri_segmentation,$val);
							$this->uri_argvs = & $temp_uri;
							$this->controller = $temp_uri[0];
							$this->action = $temp_uri[1];
							//var_dump($this->uri_argvs);
							return true;
						}
					}
				}
				unset($temp_uri);
			}
		}
		
		/**
		 * 返回从url中取出的数据,uri_argvs['controller'] uri_argvs['action'] uri_argvs['argvs']
		 *
		 * @return unknown
		 */
		public function getUriArgvs(){
			return $this->uri_argvs;
		}
		
		/**
		 * 返回操作的Controller
		 *
		 * @return unknown
		 */
		public function getController(){
			return $this->controller;
		}
		
		/**
		 * 返回操作的action
		 *
		 * @return unknown
		 */
		public function getAction(){
			return $this->action;
		}
	}
?>
